import axios from "axios";
import { MessageBox, Message } from "element-ui";
import { showScreenLoading, hideScreenLoading } from "./loading";
import store from "@/store";
import { getToken } from "@/utils/auth";

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // if(JSON.stringify(config.data).indexOf('TestMailGlobal')!== -1){
    //   hideScreenLoading(config.headers);
    // }
    if (
      config.headers.showLoading !== false &&
      JSON.stringify(config.data).indexOf("TestMailGlobal") === -1 &&
      JSON.stringify(config.data).indexOf("TestV2rayNode") === -1
    ) {
      showScreenLoading(config.headers);
    }
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers["X-Token"] = getToken();
    }
    return config;
  },
  (error) => {
    hideScreenLoading(config.headers);
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    if (response.headers.showLoading !== false) {
      hideScreenLoading();
    }
    let isdownload = response.request.responseURL.indexOf("download"); //下载接口没有StatusCode
    let isupload = response.request.responseURL.indexOf("upload"); //上传接口没有StatusCode
    const res = response.data;
    if (isdownload === -1 && isupload === -1 && res.Status.StatusCode !== 0) {
      //
      if (res.Status.StatusCode === 2000) {
        store.dispatch("user/resetToken").then(() => {
          location.reload();
        });
        // to re-login
        // MessageBox.confirm('登录状态已失效，是否重新登录', {
        //   confirmButtonText: '重新登录',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
        //   store.dispatch('user/resetToken').then(() => {
        //     location.reload()
        //   })
        // })
      } else if (res.Status.StatusCode === 12557) {
        Message({
          message: "您的授权已经过期超过15天，系统禁止登录，请您联系您的服务商。",
          type: "error",
          duration: 5 * 1000
        });
      } else if (res.Status.StatusCode === 256) {
        //邮箱测试接口返回256，错误0x100
        return res;
      } else {
        Message({
          message: res.Status.Msg2Client || "Error",
          type: "error",
          duration: 5 * 1000
        });
      }
      return Promise.reject(new Error(res.Status.Msg2Client || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    hideScreenLoading();
    console.log("err" + error); // for debug
    // 默认提示
    let msg = '请求发生错误';

    // 有响应返回才检查状态码
    if (error.response) {
      const status = error.response.status;
      switch (status) {
        case 400:
          msg = '请求参数错误';
          break;
        case 401:
          msg = '未授权，请重新登录';
          break;
        case 403:
          msg = '拒绝访问，权限不足';
          break;
        case 404:
          msg = '请求地址不存在';
          break;
        case 408:
          msg = '请求超时，请稍后再试';
          break;
        case 500:
          msg = '服务器内部错误';
          break;
        case 502:
          msg = '网关错误';
          break;
        case 503:
          msg = '服务不可用';
          break;
        case 504:
          msg = '网关超时';
          break;
        default:
          msg = `请求错误（${status}）`;
      }
    }
    // 没有响应返回（如断网）
    else if (!error.response) {
      msg = '无法连接服务器，请检查网络';
    }
    Message({
      message: msg,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
